package com.hzw.saas.service.hpc.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import com.hzw.saas.api.hpc.IHpcAccountService;
import com.hzw.saas.api.hpc.bo.HpcAccountBo;
import com.hzw.saas.api.hpc.bo.HpcAccountRecordBo;
import com.hzw.saas.service.hpc.data.HACDetail;
import com.hzw.saas.service.hpc.exception.PullHpcDetailsException;
import com.hzw.saas.service.hpc.service.AbstractHpcFetchService;
import com.hzw.saas.service.hpc.util.HpcUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 通过SSH拉取超算明细
 * </p>
 *
 * @author sonam
 * @since 2021/4/21 18:38
 */
@Slf4j
@Service("sshHpcFetchServiceImpl")
public class SshHpcFetchServiceImpl extends AbstractHpcFetchService {

    @Resource(name = "hpcAccountServiceImpl")
    private IHpcAccountService hpcAccountService;

    @Override
    protected List<HACDetail> fetchHpcDetails(HpcAccountRecordBo hpcAccountRecordBo, String startDateStr, String endDateStr) throws Exception, PullHpcDetailsException {
        // SSH  startDate <= date < endDate
        final String newEndDateStr = DateUtil.formatDate(DateUtil.offsetDay(DateUtil.parse(endDateStr), 1));
        String hpcAccountId = hpcAccountRecordBo.getHpcAccountId();
        HpcAccountBo hpcAccountBo = hpcAccountService.getById(hpcAccountId);
        if (Objects.isNull(hpcAccountBo)) {
            return new ArrayList<>();
        }

        List<HACDetail> details = new ArrayList<>();
        try {
            details.addAll(HpcUtils.pullHpcAccountDetails(hpcAccountBo, startDateStr, newEndDateStr));
        } catch (PullHpcDetailsException e) {
            log.warn(StrFormatter.format("主机地址丢失:{}或者账户{}密码{}错误", hpcAccountBo.getHost(), hpcAccountBo.getHpcAccount(), hpcAccountBo.getHpcPassword()), e);
            throw e;
        }

        return details;
    }

}
